package sample.commands
{
	import asf.controllers.FrontController;
	import asf.core.Application;
	import asf.core.Layer;
	import asf.events.ApplicationLoadProgressEvent;
	import asf.interfaces.ICommand;
	import asf.resources.URLResources;
	import asf.sections.Section;
	import asf.transitions.SampleTransitionOut;
	
	import br.com.stimuli.loading.BulkProgressEvent;
	
	import flash.events.Event;
	
	import sample.app.Commands;
	import sample.app.Globals;
	import sample.app.Sections;
	import sample.cmdparams.NavigateCommandParams;
	import sample.components.Preloader;
	
	public class NavigateCommand implements ICommand
	{
		private var params:NavigateCommandParams;
		private var app:Application;
		
		private var preloader:Preloader;
		
		public function NavigateCommand( )
		{
			SWFAddress.onChange = swfAddressOnChange;
			app = Application.getByID( Globals.APP_ID );
			
			preloader = new Preloader( );
			preloader.x = - preloader.width / 2;
			
			app.layers.preloader.addChild( preloader );
		}
		
		public function execute(...args):Boolean
		{
			params = args[ 0 ];
			
			ctrace( params.sectionID );
			
			SWFAddress.setValue( params.sectionID );
			
			return true;
		}
		
		private function swfAddressOnChange( ):void
		{
			var link:String = URLResources.getLinkByIndex( 0 );
			var section:Section;
			
			ctrace( link );
			
			if( app.navigation.sectionsIDs.indexOf( link ) == -1 )
			{
				FrontController.broadcastEvent( Commands.NAVIGATE, new NavigateCommandParams( Sections.HOME ) );
				
				return;
			}
			else
			{
				section = app.navigation.getSectionByID( link );
				
				section.addEventListener( ApplicationLoadProgressEvent.DEPENDENCIES_LOAD_START, onLoadStart );
				section.addEventListener( ApplicationLoadProgressEvent.DEPENDENCIES_LOAD_PROGRESS, onLoadProgress );
				section.addEventListener( ApplicationLoadProgressEvent.DEPENDENCIES_LOAD_COMPLETE, onLoadComplete );
				
				app.navigation.changeTo( link, app.navigation.defaultTransition, new SampleTransitionOut( ) );
				
				if( ! section.isLoaded )
				{
					( app.layers.site as Layer ).goDark( 1.5 );
					( app.layers.site as Layer ).mouseChildren = false;
					
					preloader.setProgress( 0 );
					preloader.show( );
				}
			}
		}
		
		private function onLoadStart( evt:Event ):void
		{
			ctrace( ( evt.target as Section ).id );
		}
		
		private function onLoadProgress( evt:BulkProgressEvent ):void
		{
			//ctrace( );
			preloader.setProgress( evt.percentLoaded );
		}
		
		private function onLoadComplete( evt:Event ):void
		{
			ctrace( ( evt.target as Section ).id );
			
			( app.layers.site as Layer ).goDark( 0, true );
			( app.layers.site as Layer ).mouseChildren = true;
			
			preloader.hide( );
		}
	}
}